<template>
  <div class="crop-category">
    <div class="page-header">
      <h2>农作物种类管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增种类
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="分类名称">
          <el-input
            v-model="searchForm.categoryName"
            placeholder="请输入分类名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="分类编码">
          <el-input
            v-model="searchForm.categoryCode"
            placeholder="请输入分类编码"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="categoryCode" label="分类编码" width="200" />
        <el-table-column prop="categoryName" label="分类名称" min-width="150" />
        <el-table-column prop="description" label="分类描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="parentName" label="父级分类" width="180" />
        <el-table-column prop="level" label="层级" width="150">
          <template #default="{ row }">
            <el-tag :type="getLevelType(row.level)">{{ row.level }}级</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="150">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="success" link size="small" @click="handleAddChild(row)">
              <el-icon><Plus /></el-icon>
              添加子类
            </el-button>
            <el-button 
              type="danger" 
              link 
              size="small" 
              @click="handleDelete(row)"
              :disabled="row.children && row.children.length > 0"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="分类编码" prop="categoryCode">
          <el-input
            v-model="formData.categoryCode"
            placeholder="请输入分类编码"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input
            v-model="formData.categoryName"
            placeholder="请输入分类名称"
          />
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :data="categoryTree"
            check-strictly
            :props="treeProps"
            placeholder="请选择父级分类"
            clearable
            :disabled="isEdit && formData.level === 1"
          />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const tableData = ref([])
const categoryTree = ref([])

// 搜索表单
const searchForm = reactive({
  categoryName: '',
  categoryCode: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  id: '',
  categoryCode: '',
  categoryName: '',
  description: '',
  parentId: 0,
  level: 1,
  status: 1
})

// 表单验证规则
const formRules = {
  categoryCode: [
    { required: true, message: '请输入分类编码', trigger: 'blur' }
  ],
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ]
}

// 树形选择器配置
const treeProps = {
  value: 'id',
  label: 'categoryName',
  children: 'children'
}

// 计算属性
const isEdit = computed(() => !!formData.id)
const dialogTitle = computed(() => isEdit.value ? '编辑分类' : '新增分类')

// 方法
const getLevelType = (level) => {
  const types = ['', 'success', 'warning', 'info']
  return types[level] || 'info'
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadTableData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    categoryName: '',
    categoryCode: '',
    status: ''
  })
  pagination.currentPage = 1
  loadTableData()
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadTableData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadTableData()
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const handleAddChild = (row) => {
  resetForm()
  formData.parentId = row.id
  formData.level = row.level + 1
  dialogVisible.value = true
}

const handleEdit = (row) => {
  resetForm()
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${row.categoryName}" 吗？`,
      '提示',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    // 调用删除API
    // await deleteCategory(row.id)
    ElMessage.success('删除成功')
    loadTableData()
  } catch (error) {
    // 用户取消删除
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 调用保存API
    if (isEdit.value) {
      // await updateCategory(formData)
      ElMessage.success('更新成功')
    } else {
      // await addCategory(formData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: '',
    categoryCode: '',
    categoryName: '',
    description: '',
    parentId: 0,
    level: 1,
    status: 1
  })
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    // const response = await getCategoryList({
    //   ...searchForm,
    //   page: pagination.currentPage,
    //   size: pagination.pageSize
    // })
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        categoryCode: 'VEGETABLE',
        categoryName: '蔬菜',
        description: '各类蔬菜作物',
        parentId: 0,
        parentName: '-',
        level: 1,
        status: 1,
        children: [
          {
            id: 2,
            categoryCode: 'LEAF_VEGETABLE',
            categoryName: '叶菜类',
            description: '以叶片为食用部分的蔬菜',
            parentId: 1,
            parentName: '蔬菜',
            level: 2,
            status: 1,
          }
        ]
      },
      {
        id: 3,
        categoryCode: 'FRUIT',
        categoryName: '水果',
        description: '各类水果作物',
        parentId: 0,
        parentName: '-',
        level: 1,
        status: 1,
      }
    ]
    
    tableData.value = mockData
    pagination.total = mockData.length
    loadCategoryTree()
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载分类树
const loadCategoryTree = () => {
  // 构建树形数据
  categoryTree.value = tableData.value.map(item => ({
    ...item,
    children: item.children || []
  }))
}

onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.crop-category {
  padding: 20px;
  background: white;
  border-radius: 8px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: flex-end;
}
</style>